module( ..., package.seeall )

local MetaTable = {
	__index = getfenv(),
	__tostring = function( tbl )
		return "Node(" .. tbl.id .. ")"
	end
}

function New( id )
	
	local o = {
		id = id,
		neighbors = {}
	}
	
	setmetatable( o, MetaTable )
	
	return o
	
end

function breadthFirstSearch( self )
	
	local level = 0
	local levelTable = {
		[self] = level
	}
	local neighbors = self.neighbors --Start with the nodes around this member
	
	while true do
		
		level = level + 1 --Increase the current layer by one
		
		for _, node in ipairs( neighbors ) do
			levelTable[ node ] = level
		end
		
		local nextNeighbors = {}
		
		for _, node in pairs( neighbors ) do
			
			for _, neighbor in ipairs( node.neighbors ) do
				if levelTable[ neighbor ] == nil then
					table.insert( nextNeighbors, neighbor )
				end
			end
			
		end
		
		if #nextNeighbors == 0 then
			break
		end
		
		neighbors = nextNeighbors
		
	end
	
	return levelTable
end

function addUndirectedNeighbor( self, node )
	table.insert( self.neighbors, node )
	table.insert( node.neighbors, self )
end

function addDirectedNeighbor( self, node )
	table.insert( self.neighbors, node )
end